// 查询 ArcGIS 要素
import {EsriJSON} from 'ol/format'; // 引入 EsriJSON 格式

// 添加超时功能的 fetch
function fetchWithTimeout(url, options = {}, timeout = 10000) { // 默认超时时间为10秒
  return Promise.race([
    fetch(url, options),
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('Request timed out')), timeout)
    )
  ]);
}

// 主函数，用于执行查询操作
export async function executeFeatureQuery(layerNames, BASE_URL, API_KEY) {
  try {
    if (typeof layerNames === 'string') {
      layerNames = [layerNames];
    }

    // 并行执行多个图层的查询操作，使用 Promise.allSettled
    const allFeatures = await Promise.allSettled(
      layerNames.map(async (layerName) => {
        const layerId = await fetchLayerId(BASE_URL, API_KEY, layerName);
        console.log(`图层 ${layerName} 的 ID`, layerId);
        const queryUrl = `${BASE_URL}/${layerId}/query?key=${API_KEY}`;
        return fetchArcgisFeatures(queryUrl, "1=1", null);
      })
    );

    // 处理结果，将成功和失败的结果区分开
    return allFeatures.map((result, index) => {
      if (result.status === "fulfilled") {
        return result.value;
      } else {
        console.error(`Error fetching features for layer ${layerNames[index]}:`, result.reason);
        return {error: result.reason.message};
      }
    });
  } catch (error) {
    console.error("Error:", error);
    throw error;
  }
}

// 发送请求并返回所有图层数据
export async function fetchAllLayers(url) {
  try {
    const response = await fetchWithTimeout(url, {
      headers: {"Content-Type": "application/x-www-form-urlencoded"},
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("Error fetching layers data:", error);
    throw error;
  }
}

// 从数据中查找指定名称的图层 ID
export function findLayerId(layers, layerName) {
  const targetLayer = layers.find((layer) => layer.name === layerName);
  if (targetLayer) {
    return targetLayer.id;
  } else {
    throw new Error(`Layer with name ${layerName} not found`);
  }
}

// 获取指定图层名称的 ID
export async function fetchLayerId(baseUrl, apiKey, layerName) {
  const url = `${baseUrl}?f=json&key=${apiKey}`;
  try {
    const data = await fetchAllLayers(url);
    const layerId = findLayerId(data.layers, layerName);
    return layerId;
  } catch (error) {
    console.error("Error fetching layer ID:", error);
    throw error;
  }
}

// 查询 ArcGIS 要素
export async function fetchArcgisFeatures(url, filter, geometry = null, timeout = 10000) {
  const esriFormat = new EsriJSON();
  const params = new URLSearchParams({
    f: "json",
    where: filter,
    outFields: "*",
    returnGeometry: true,
    spatialRel: "esriSpatialRelIntersects"
  });

  // 确定几何类型并添加到参数
  if (geometry) {
    // 处理几何逻辑...
  } else {
    params.append("geometryType", "esriGeometryEnvelope");
    params.append("geometry", JSON.stringify({
      xmin: -180,
      ymin: -90,
      xmax: 180,
      ymax: 90,
      spatialReference: { wkid: 4326 }
    }));
  }

  try {
    // 发起请求
    const response = await fetchWithTimeout(url, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: params.toString(),
    }, timeout);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 解析响应数据
    const data = await response.json();
    const features = esriFormat.readFeatures(data);

    // 保存必要的信息，包括 fields, geometryType 和 spatialReference
    const fields = data.fields;
    const geometryType = data.geometryType;
    const spatialReference = data.spatialReference;

    // 处理特征以确保坐标和所有属性信息完整
    return features.map((feature) => {
      const geometry = feature.getGeometry();
      const coordinates = geometry.getCoordinates();

      // 确保坐标有效
      if (!coordinates || coordinates.length === 0) {
        console.warn('Invalid coordinates for feature:', feature);
      }

      // 获取属性并设置到特征中
      const properties = feature.getProperties();

      // 保存所有信息到特征属性
      feature.setProperties({
        ...properties,
        fields,              // 保存所有字段信息
        geometryType,        // 保存几何类型
        spatialReference,     // 保存空间参考
        displayFieldName: data.displayFieldName // 保存显示字段名称
      });

      return feature; // 返回处理后的特征
    }); // 返回处理后的特征数组
  } catch (error) {
    console.error("Error fetching ArcGIS features:", error);
    throw error;
  }
}

